import { defineComponent, nextTick } from 'vue';
import { getLngLat } from './mapUtils.js';
import icon from './assets/marker_red.png?url';

export default defineComponent({
  name: 'CMapPositionPicker',
  emits: ['update:modelValue', 'update:modelValue', 'update:modelValue', 'update:lng', 'update:lat', 'change'],
  props: {
    modelValue: undefined,
    lng: undefined,
    lat: undefined,
    useString: undefined,
    useArray: undefined,
    autoFitView: undefined,
    disabled: undefined,
  },
  render() {
    return null;
  },
  computed: {
    lngLat() {
      let lngLat = getLngLat(this.modelValue);
      if (!lngLat) {
        lngLat = getLngLat([this.lng, this.lat]);
      }
      return lngLat ? lngLat.join(',') : '';
    },
  },
  inject: {
    useMap: { default: () => {} },
  },
  created() {
    this.map = this.useMap();
    this.position = null;
    this.icon = new BMapGL.Icon(icon, new BMapGL.Size(24, 26), {
      anchor: new BMapGL.Size(12, 26),
    });
    this.createMarker = (lnglat) => {
      let [lng, lat] = getLngLat(lnglat) || [];
      if (!lng || !lat) return;
      let point = new BMapGL.Point(lng, lat);
      if (!this.marker) {
        this.marker = new BMapGL.Marker(point, { icon: this.icon });
        this.map.addOverlay(this.marker);
      } else {
        this.marker.setPosition(point);
      }
      if (this.autoFitView === true) {
        this.map.setViewport([point]);
      }
    };
    this.handleClick = ({ latlng }) => {
      let { lng, lat } = latlng;
      this.position = lng + ',' + lat;
      this.createMarker(this.position);
      if (this.useArray === true) {
        this.$emit('update:modelValue', [lng, lat]);
      } else if (this.useString !== false) {
        this.$emit('update:modelValue', lng + ',' + lat);
      } else {
        this.$emit('update:modelValue', latlng);
      }
      this.$emit('update:lng', lng);
      this.$emit('update:lat', lat);
      this.$emit('change', latlng);
    };
    this.open = () => {
      this.map.addEventListener('click', this.handleClick);
    };
    this.close = () => {
      this.map.removeEventListener('click', this.handleClick);
    };
    this.$watch(
      () => this.lngLat,
      () => {
        if (this.lngLat !== this.position) {
          this.createMarker(this.lngLat);
        }
      },
      { immediate: true }
    );
    this.$watch(
      () => this.disabled,
      (disabled) => {
        disabled !== true ? this.open() : this.close();
      },
      { immediate: true }
    );
  },
  beforeUnmount() {
    this.close();
  },
});
